﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Web.CrmContacto.Code;
using Web.Framework.Translate;
using Web.Framework;
using CrmContacto.Contracts.Contracts;
using CrmContacto.Contracts.Contracts.Search;
using CrmContacto.WebApp.Code.InnerClasses;
using CrmContacto.Contracts.Enums;
using CrmContacto.Contracts;
using CrmContacto.WebApp.Code.InnerClasses.FrontEnd.Promociones;
using CrmContacto.Contracts.Promociones;
using Web.Framework.Search;
using Web.Framework.Helpers;
using System.Text;

namespace CrmContacto.WebApp.App
{
    public partial class ReporteParticipantesPosiblesEnPromocion : BasePage
    {
        private List<AccionDeMarketingPromocion> PromocionesCurrentList
        {
            get
            {
                return (List<AccionDeMarketingPromocion>)ViewState["PromocionesCurrentList"];
            }
            set
            {
                ViewState["PromocionesCurrentList"] = value;
            }
        }

        public AccionDeMarketingPromocion PromocionCurrent { get; set; }

        public IPromocionWebStrategy PromocionStrategy
        {
            get
            {
                return (IPromocionWebStrategy)ViewState["PromocionStrategy"];
            }
            set
            {
                ViewState["PromocionStrategy"] = value;
            }
        }

        private bool extraControlsLoaded = false;
        protected override void OnPreInit(EventArgs e)
        {
            // Cargo los controles para que tambien se mantengan los valores postback
            if (PromocionStrategy != null)
            {
                // Cargar los controles adicionales.
                PromocionStrategy.LoadExtraControls(this.pnlExtraControls);
                extraControlsLoaded = true;
            }
        }


        // Accesors
        public string ContactosText
        {
            get { return this.txtContactosEmail.Text; }
        }

        public bool? AplicaCupon
        {
            get
            {
                bool? aplica = null;
                var id = UIHelper.GetIntFromInputCbo(this.cboSubConjuntoDeAplicacion);
                if (id.HasValue)
                {
                    aplica = id.Value == (int)eSiNo.Si;
                }

                return aplica;
            }
        }

        private List<LinkButton> actionButtons = new List<LinkButton>();
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            // Asigno la promoción actual            
            AsignarPromocionActual();

            if (PromocionStrategy != null && !extraControlsLoaded)
            {
                // Sino entro antes Cargo los controles sin los valores postback
                // Cargar los controles adicionales.
                PromocionStrategy.LoadExtraControls(this.pnlExtraControls);
            }

            //LinkButton seleccionarListasButton = new LinkButton();
            //seleccionarListasButton.ID = "BoAccionDeMktgMenuAgregarAccionAAccion";

            //if (base.NavigationContext.AgregandoAccionesDeMarketingAAccionDeMarketing)
            //{
            //    seleccionarListasButton.Text = LocalizationProvider.Instance["Bo.AccionDeMarketing.ActionMenu.AgregarAccionRelacionadaAAccionDeMarketing"];
            //}           

            //seleccionarListasButton.Click += new EventHandler(seleccionarListasButton_Click);
            //actionButtons.Add(seleccionarListasButton);
            //seleccionarListasButton.Visible = base.NavigationContext != null && (base.NavigationContext.AgregandoAccionesDeMarketingAAccionDeMarketing);

            base.LoadContextActions(actionButtons);
        }

        private void AsignarPromocionActual()
        {
            if (PromocionesCurrentList != null && this.cboPromociones.SelectedIndex >= 0)
            {
                PromocionCurrent = PromocionesCurrentList.Where(p => p.Id == Convert.ToInt32(this.cboPromociones.SelectedValue)).SingleOrDefault();
                if (PromocionCurrent != null)
                {
                    PromocionStrategy = PromocionWebFactory.GetPromocionStrategy(PromocionCurrent);
                }
            }
        }

        private void Volver()
        {
            if (base.NavigationContext != null && !String.IsNullOrEmpty(base.NavigationContext.UrlToGoBack))
            {
                Response.Redirect(base.NavigationContext.UrlToGoBack, true);
            }
        }

        private void SetThisPageToGoBack()
        {
            this.NavigationContext.UrlToGoBack = Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlReporteParticipantesPorPromocion;
        }

        protected override void OnPreLoad(EventArgs e)
        {
            base.OnPreLoad(e);

            //if (!base.NavigationContext.AgregandoAccionesDeMarketingAAccionDeMarketing)
            //{
            //    this.Grid.Columns[0].Visible = false;
            //}
            //else
            //{
            //    this.Grid.Columns[2].Visible = false;
            //    this.Grid.Columns[3].Visible = false;

            //    TitleNavContext.Visible = true;

            //    if (base.NavigationContext.AgregandoAccionesDeMarketingAAccionDeMarketing)
            //        lblContexto.Text = LocalizationProvider.Instance["Bo.AccionesDeMktg.Context.AgregandoAccionesAAccionDeMarketing"];                
            //}
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                this.lnkBuscar.Attributes.Add("aspnetid", this.lnkBuscar.ClientID);

                // Analizar si se esta usando para agregar en acciones de marketing, en donde hardcodeo el plan al q pertenece y los tipos válidos
                //?planDeMarketingId={0}&discriminadorId
                // HasPermissionToSeeMe(PlanProdSecurity.DESTINO_VER);
                if (!this.IsPostBack)
                {

                    pnlResults.Visible = false;                   

                    this.LoadCbos();                   
                }
                else
                {
                    RegisterPromocionesIntoJS(PromocionesCurrentList);
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void LoadCbos()
        {
            UIHelper.LoadEstados<eSiNo>(this.cboSubConjuntoDeAplicacion, LocalizationProvider.Instance["DropDown.Todos"]);

            LoadCboPromociones();

            // registros para la paginacion
            List<KeyValuePair<string, string>> opcionesParaPaginar = new List<KeyValuePair<string, string>>();
            opcionesParaPaginar.Add(new KeyValuePair<string, string>("10", "10"));
            opcionesParaPaginar.Add(new KeyValuePair<string, string>("20", "20"));
            opcionesParaPaginar.Add(new KeyValuePair<string, string>("50", "50"));
            opcionesParaPaginar.Add(new KeyValuePair<string, string>("100", "100"));
            opcionesParaPaginar.Add(new KeyValuePair<string, string>("500", "500"));
            opcionesParaPaginar.Add(new KeyValuePair<string, string>("1000", "1000"));
            opcionesParaPaginar.Add(new KeyValuePair<string, string>("0", LocalizationProvider.Instance["DropDown.Todos"]));
            UIHelper.LoadCbo(opcionesParaPaginar, this.cboRegistros, string.Empty, "Key", "Value");

            this.cboRegistros.SelectedValue = "20";

            //UIHelper.LoadEstados<EstadoPlanDeMarketing>(this.chkEstado, string.Empty);
        }

        private void LoadCboPromociones()
        {
            AccionDeMarketingSearch search = new AccionDeMarketingSearch();
            search.DiscriminadorIdList.Add((int)DiscriminadorAccionDeMarketing.Promocion);

            DateTime? fechaDesde = UIHelper.GetDateTimeFromInputText(this.txtFechaDesde.Text);
            DateTime? fechaHasta = UIHelper.GetDateTimeFromInputText(this.txtFechaHasta.Text);
            search.EmpresaId = BasePage.CompanyId;
            //search.FechaEventoDesde = fechaDesde;
            //search.FechaEventoHasta = fechaHasta;

            List<AccionDeMarketingPromocion> promocionesList = WebServiceHelper.GetAccionesDeMarketingPromocion(search);
            PromocionesCurrentList = promocionesList;
            UIHelper.LoadCbo(promocionesList, cboPromociones, string.Empty);

            RegisterPromocionesIntoJS(PromocionesCurrentList);
        }

        private void RegisterPromocionesIntoJS(List<AccionDeMarketingPromocion> promocionesList)
        {
            // Tengo que registrar el array en javascript
            StringBuilder builder = new StringBuilder();
            string separador = string.Empty;
            builder.Append("<script type='text/javascript' >");
            builder.Append("var promociones = [];");
            DateTime now = DateTime.Now;
            foreach (AccionDeMarketingPromocion promo in promocionesList)
            {
                var promoStrategy = PromocionWebFactory.GetPromocionStrategy(promo);

                //builder.AppendFormat("companies[{0}] = '{1}';", companyConfiguration.CompanyId, companyConfiguration.LogoImgFilePath);
                DateTime desde = promo.FechaDesde.HasValue ? promo.FechaDesde.Value : new DateTime(now.Year, now.Month, 1);
                DateTime hasta = promo.FechaHasta.HasValue ? promo.FechaHasta.Value : new DateTime(now.Year, now.Month, 1).AddMonths(1).AddDays(-1);
                bool usaCupon = false;
                if (promoStrategy != null)
                {
                    usaCupon = promoStrategy.UsaCupon;
                }

                builder.AppendFormat("promociones[{0}] = '{1:dd/MM/yyyy}##{2:dd/MM/yyyy}##{3}';", promo.Id, desde, hasta, usaCupon ? "1" : "0");
            }

            builder.Append("</script>");
            Page.ClientScript.RegisterStartupScript(typeof(string), "promociones", builder.ToString());
        }

        protected override void ApplySecurity()
        {
            //this.btnAgregarNuevo.Visible = HasPermissionFor(PlanProdSecurity.DESTINO_CREAR);

            //if (this.Grid.DataSource != null)
            //{
            //    this.Grid.Columns[0].Visible = HasPermissionFor(PlanProdSecurity.DESTINO_EDITAR);
            //    this.Grid.Columns[1].Visible = HasPermissionFor(PlanProdSecurity.DESTINO_ELIMINAR);
            //}
        }

        public ParticipantesSearch ParticipantesSearch = new ParticipantesSearch();
        private void Buscar()
        {
            LoadSearch();

            //PromocionStrategy.LoadGridFromSearch(search);  

            this.cboPromociones.Attributes.Add("nochange", "nochange");

            BindToGrid();
            pnlResults.Visible = true;
        }

        private void LoadSearch()
        {
            AsignarPromocionActual();
            ParticipantesSearch = PromocionStrategy.GetParticipantesSearch(this);
        }

        private void BindToGrid()
        {
            int pageSize = Convert.ToInt32(cboRegistros.SelectedValue);
            if (pageSize == 0)
            {
                this.Grid.AllowPaging = false;
            }
            else
            {
                this.Grid.AllowPaging = true;
                ParticipantesSearch.PageSize = this.Grid.PageSize = pageSize;
            }

            this.Grid.DataSourceID = "CustomerObjectDs";
        }

        public SearchParticipantesObjDataSourceProvider ParticipanteSearchProvider { get; set; }

        protected void CustomerObjectDs_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
        {
            GridViewSearchObjectDataSource searchProvider = new GridViewSearchObjectDataSource();

            this.ParticipanteSearchProvider = new SearchParticipantesObjDataSourceProvider();
            ParticipanteSearchProvider.WebServiceHelper = this.WebServiceHelper;
            this.ParticipanteSearchProvider.Page = this;
            //this.CustomerSearchProvider.SearchParam = this.CustomerSearchParamSession;
            //this.cu SearchParticipantesObjDataSourceProvider

            searchProvider.Provider = this.ParticipanteSearchProvider;
            e.ObjectInstance = searchProvider;
        }

        protected void Grid_Selected(object sender, ObjectDataSourceStatusEventArgs e)
        {
            try
            {
                if (e.Exception != null)
                {
                    ExceptionManager.Instance.HandleException(e.Exception);
                    e.ExceptionHandled = true;
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void Grid_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "editar")
                {
                    int contactoId = Convert.ToInt32(this.Grid.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
                    SetThisPageToGoBack();
                    this.Response.Redirect(string.Format(Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlCustomerEdit + "?Id={0}", contactoId), true);
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void Grid_DataBound(object sender, EventArgs e)
        {
            try
            {
                if (ParticipanteSearchProvider != null)
                {
                    // Todo, con el strategy ocultar las columnas que no van

                    ParticipantesSearchResult searchResult = ParticipanteSearchProvider.SearchResult;

                    if (searchResult != null && searchResult.TotalDeResultados > 0)
                    {
                        this.pnlResults.CssClass = "displayBlock";
                        this.imgExpandResults.ImageUrl = "/Images/icon_blockexpanded.png";
                        string resultStr = string.Format(LocalizationProvider.Instance["Bo.SearchContacto.ResultString"], searchResult.TotalDeResultados);
                        lblSearchResult.Text = resultStr;

                        //RePopulateValues();
                    }
                    else
                    {
                        lblSearchResult.Text = LocalizationProvider.Instance["Bo.SearchContacto.NoResultsString"];
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void Grid_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                this.Grid.PageIndex = e.NewPageIndex;

                LoadSearch();

                BindToGrid();
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void Grid_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    Cliente cliente = (Cliente)e.Row.DataItem;

                    int tipoDocIndex = 4;
                    if (cliente.TipoDocumentoId.HasValue)
                    {
                        foreach (var liDocItem in this.GetTipoDocumento(0))
                        {
                            if (Convert.ToInt32(liDocItem.Id) == cliente.TipoDocumentoId.Value)
                            {
                                e.Row.Cells[tipoDocIndex].Text = liDocItem.Nombre;
                                break;
                            }
                        }
                    }
                    else
                    {
                        e.Row.Cells[tipoDocIndex].Text = string.Empty;
                    }


                    int origenPuntoDeVentaIndex = 6;
                    if (cliente.OrigenPuntoDeVentaId.HasValue)
                    {
                        e.Row.Cells[origenPuntoDeVentaIndex].Text = this.GetPuntosDeVenta(cliente.EmpresaId).Where(p => p.Id == cliente.OrigenPuntoDeVentaId.Value).Single().Nombre;
                    }
                    else
                    {
                        e.Row.Cells[origenPuntoDeVentaIndex].Text = string.Empty;
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void lnkBuscar_Click(object sender, EventArgs e)
        {
            try
            {
                Buscar();
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void lnkExportarAExcel_Click(object sender, EventArgs e)
        {
            try
            {
                this.Grid.AllowPaging = false;

                string dataSourceId = Grid.DataSourceID;
                Grid.DataSourceID = null;

                LoadSearch();

                // Obtengo los valores con WS
                int pageSize = this.ParticipantesSearch.PageSize;
                int pageSkip = this.ParticipantesSearch.PageSkip;

                this.ParticipantesSearch.PageSize = 0;
                this.ParticipantesSearch.PageSkip = 0;

                var resultados = WebServiceHelper.GetParticipantes(this.ParticipantesSearch);

                Grid.DataSource = resultados.Resultados;
                Grid.DataBind();

                GridViewExportExcelUtil.Export("Participantes.xls", this.Grid);

                this.ParticipantesSearch.PageSize = pageSize;
                this.ParticipantesSearch.PageSkip = pageSkip;
                this.Grid.AllowPaging = true;
                Grid.DataSourceID = dataSourceId;
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }
    }
}
